import 'dart:async';
import 'dart:developer';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/constant/order_constant.dart';
import 'package:guochaoapp/common/constant/to_order_detail_source.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/config/container.dart';
import 'package:guochaoapp/controller/shopping/shopping_controller.dart';
import 'package:guochaoapp/model/order_detail_entity.dart';
import 'package:guochaoapp/model/payment_entity.dart';
import 'package:guochaoapp/model/paymentinit_entity.dart';
import 'package:guochaoapp/model/transterpay_entity.dart';
import 'package:guochaoapp/model/wechatpay_entity.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';
import 'package:tobias/tobias.dart' as tobias;

class GCShoppingPaymentController extends GetxController {
  UserService userService = Get.find();

  var selectedIndex = 0.obs;
  var mallOrderNo;
  var paymentinitData = PaymentinitData().obs;

  Timer timer;

  var countdown = 3600.obs;

  requestPayMentInit() {
    if (mallOrderNo != null) {
      HttpClient.request<PaymentinitEntity>(
          url: MallApi.payment_init,
          method: Method.GET,
          params: {
            "mallOrderNo": mallOrderNo,
            "uid": userService.userInfo.uid
          },
          onSuccess: (_, model) {
            var expireTimeStampDate = DateTime.fromMillisecondsSinceEpoch(model.data.expireTimeStamp);//将拿到的时间戳转化为日期
            countdown.value = expireTimeStampDate.difference(DateTime.now()).inSeconds;
            selectedIndex.value = 0;
            paymentinitData.value = model.data;

            if(timer != null) {
              timer.cancel();
              timer = null;
            }

            timer = Timer.periodic(Duration(seconds: 1), (timer) {
              countdown.value = countdown.value - 1;
            });
          },
          onFailed: (error) {
            EasyLoading.showError(error);
          });
    } else {
      log("get.arguments mallOrderNo is null");
    }
  }

  getDisplayTime() {
    if(countdown.value > 86400) {
      return (countdown.value / 86400).toInt().toString() + "天" + (countdown.value / 3600).toInt().toString() + "小时" + (countdown.value / 60 % 60).toInt().toString() + "分钟" + (countdown.value % 60).toString() + "秒";
    } else {
      return (countdown.value / 3600).toInt().toString() + "小时" + (countdown.value / 60 % 60).toInt().toString() + "分钟" + (countdown.value % 60).toString() + "秒";
    }

  }

  submitTap() async {
    if (selectedIndex.value == 1) {

      if (mallOrderNo != null) {
        HttpClient.request<WechatpayEntity>(
            url: MallApi.payment,
            method: Method.POST,
            data: {
              "mallOrderNo": mallOrderNo,
              "payChannel": "wx",
              "uid": userService.userInfo.uid
            },
            onSuccess: (_, model)  {
              fluwx.payWithWeChat(
                  appId: model.data.wxPayParams.appid,
                  partnerId: model.data.wxPayParams.partnerid,
                  prepayId: model.data.wxPayParams.prepayid,
                  packageValue: model.data.wxPayParams.package,
                  nonceStr: model.data.wxPayParams.noncestr,
                  timeStamp: model.data.wxPayParams.timestamp,
                  sign: model.data.wxPayParams.sign).then((res) {
                    log(res.toString());
              });
            },
            onFailed: (error) {
              EasyLoading.showError(error);
            });
      }

    } else if (selectedIndex.value == 2) {
      if (mallOrderNo != null) {
          HttpClient.request<PaymentEntity>(
            url: MallApi.payment,
            method: Method.POST,
            data: {
              "mallOrderNo": mallOrderNo,
              "payChannel": "ali",
              "uid": userService.userInfo.uid
            },
            onSuccess: (_, model)  {
              tobias.aliPay(model.data.aliPayParams).then((res) {
                  var resultStatus = res["resultStatus"].toString();

                  if(resultStatus == "9000") {
                    Get.toNamed(Routes.ORDER_DETAIL, arguments: [mallOrderNo, OrderConstant.statusInit, ToOrderDetailSource.paymentTo]);
                  } else {
                     Get.toNamed(Routes.PAYMENT_FAIL, arguments: {
                      "mallOrderNo" : mallOrderNo
                    }).then((value) {
                        requestPayMentInit();
                     });
                  }

              });
            },
            onFailed: (error) {
              EasyLoading.showError(error);
            });
      }

    } else if (selectedIndex.value == 3) {
      if (mallOrderNo != null) {
        HttpClient.request<TransterpayEntity>(
            url: MallApi.payment,
            method: Method.POST,
            data: {
              "mallOrderNo": mallOrderNo,
              "payChannel": "transfer",
              "uid": userService.userInfo.uid
            },
            onSuccess: (_, model)  {
              Get.toNamed(Routes.PAYMENT_TRANSFER,
                  arguments: {"mallOrderNo" : mallOrderNo,"price": Get.parameters, "data" : model.data.receiptCard});
            },
            onFailed: (error) {
              EasyLoading.showError(error);
            });
      }

    } else if (selectedIndex.value == 4) {
      if (mallOrderNo != null) {
        HttpClient.request<PaymentEntity>(
            url: MallApi.payment,
            method: Method.POST,
            data: {
              "mallOrderNo": mallOrderNo,
              "payChannel": "credit",
              "uid": userService.userInfo.uid
            },
            onSuccess: (_, model)  {
              Get.toNamed(Routes.PAYMENT_TRANSFER,
                  arguments: {"price": Get.parameters});
            },
            onFailed: (error) {
              EasyLoading.showError(error);
            });
      }
    }
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    fluwx.weChatResponseEventHandler.listen((res) {
      if (res is fluwx.WeChatPaymentResponse) {
        log(res.errCode.toString());
        // do something here
        if(res.errCode.toString() == "0") {
          Get.toNamed(Routes.ORDER_DETAIL, arguments: [mallOrderNo, OrderConstant.statusInit,ToOrderDetailSource.paymentTo]);
        } else {
          Get.toNamed(Routes.PAYMENT_FAIL,  arguments: {
            "mallOrderNo" : mallOrderNo
          }).then((value) {
            requestPayMentInit();
          });
        }
      }
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    timer.cancel();
    timer = null;
  }
}
